package com.mvc.framework.context;


import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

public class GPApplicationContext  {

    private Properties config = new Properties();

    private Map<String,Object> instanceMapping = new ConcurrentHashMap<String, Object>();

    //类似于内部的配置信息，我们在外面是看不到的
    //我们能够看到的只有ioc容器  getBean方法来间接调用的
    private List<String> classCache = new ArrayList<String>();

    public GPApplicationContext(String location){

        InputStream is;
        try{
            is=this.getClass().getClassLoader().getResourceAsStream(location);
            config.load(is);
        String pachageName = config.getProperty("scanPackage");
        doRegister(pachageName);
        doCreateBean();

        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("IOC 容器已经初始化");
    }

    //把符合条件所有的class全部找出来，注册到缓存里面去
    private void doRegister(String packageName) {
     URL url = this.getClass().getClassLoader().getResource("/"+packageName.replaceAll("\\.","/"));
     File dir =new File(url.getFile());
     for (File file : dir.listFiles()) {
        if(file.isDirectory()){
            doRegister(packageName+"."+file.getName());
        }else {
            classCache.add(packageName+"."+file.getName().replace(".class", ""));
        }
     }

    }
    /**
     * 创建Bean 依赖循环问题等
     */
    private void doCreateBean() {
        if(classCache.size() == 0){ return; }
        try {
            for (String className : classCache) {
                Class<?> clazz = Class.forName(className);

            }
        }catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 将首字母小写
     * @param str
     * @return
     */
    private String lowerFirstChar(String str){
        char [] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }


    public Map<String,Object> getAll(){
        return instanceMapping;
    }


    public Properties getConfig() {
        return config;
    }


}
